﻿using System;
using System.Collections.Generic;
using StockEngine.Extensions;
using StockEngine.RealTime;
using StockModel;

namespace StockEngine
{
	internal class GroupInitializerBase
	{
		#region Properties

		public List<EngineStockGroup> Groups { get; private set; }

		protected StockGroupDataSource GroupDataSource { get; private set; }
		protected QuotationDataSource QuotationDataSource { get; private set; }
		protected bool IsParallelEnabled { get; set; }

		#endregion

		#region Public Methods

		public GroupInitializerBase(StockGroupDataSource groupDataSource, QuotationDataSource quotationDataSource, bool parallelEnabled)
		{
			this.GroupDataSource = groupDataSource;
			this.QuotationDataSource = quotationDataSource;
			this.IsParallelEnabled = parallelEnabled;

			this.Groups = new List<EngineStockGroup>();
			this.CreateGroups();
		}

		protected void LoadDailyQuotationsToStock(StockGroup stockGroup, Stock stock, DateTime dayToLoad)
		{
			// Load existent quotations or create a new day
			if (this.QuotationDataSource.ExistDay(stock, dayToLoad))
			{
				IEnumerable<Quotation> quotations = this.QuotationDataSource.GetQuotations(stock, dayToLoad, stockGroup.Market);
				stock.QuotationCalendar.LoadDay(dayToLoad, quotations);
			}

			this.LoadPreviousClosingValue(stockGroup, stock, dayToLoad);
		}

		protected void LoadPreviousClosingValue(StockGroup stockGroup, Stock stock, DateTime loadedDay)
		{
			DateTime previousDay = stockGroup.Market.FindPreviousWorkingDay(loadedDay);

			// Load previous closing day
			if (this.QuotationDataSource.ExistDay(stock, previousDay))
			{
				stock.QuotationCalendar.GetDay(loadedDay).DailyKeyQuotations.PreviousClosing = this.QuotationDataSource.GetClosedQuotation(stock, previousDay, stockGroup.Market);
			}
		}

		#endregion

		#region Private Methods

		private void CreateGroups()
		{
			foreach (StockGroupName name in Enum.GetValues(typeof(StockGroupName)))
			{
				EngineStockGroup group = new EngineStockGroup(name);
				this.Groups.Add(group);
			}
		}

		#endregion

	}
}
